import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import repairService from "@/api/services/eam/repairService";
import { Form, Input } from "antd";
import { toast } from "sonner";
import type { EamEquipmentRepairReport } from "./entity";

const { TextArea } = Input;

interface EamEquipmentRepairReportProps {
  parentId?: React.Key;
  isView?: boolean; // 是否只读
}

export interface EamEquipmentRepairReportHandles {
  getReport: () => EamEquipmentRepairReport;
}

const EamEquipmentRepairReportPage = forwardRef<
  EamEquipmentRepairReportHandles,
  EamEquipmentRepairReportProps
>(({ parentId, isView }, ref) => {
  const [editingData, setEditingData] = useState<EamEquipmentRepairReport>({
    repairId: parentId,
  } as EamEquipmentRepairReport);
  const [form] = Form.useForm();

  // 表单值变化时实时更新 editingData
  const handleValuesChange = (
    changedValues: Partial<EamEquipmentRepairReport>,
    allValues: EamEquipmentRepairReport
  ) => {
    setEditingData((prev) => ({
      ...prev,
      ...changedValues,
      ...allValues, // 确保获取所有最新值
    }));
  };

  useImperativeHandle(
    ref,
    () => ({
      getReport: () => editingData
    }),
    [editingData]
  );

  //加载表格数据
  const initData = () => {
    if (!parentId) return;
    repairService
      .getReport(parentId)
      .then((res) => {
        if (res) {
          form.setFieldsValue(res);
          setEditingData(res);
        }  
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    if (parentId) {
      initData();
    }
  }, [parentId]);

  return (
    <>
      <Form 
        form={form}
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 22 }}
        onValuesChange={handleValuesChange}
        disabled={isView}
      >
        <Form.Item name="repairId" label="维修单ID" hidden>
          <Input />
        </Form.Item>
        <Form.Item
          name="breakdownDescription"
          label="故障描述"
          rules={[{ required: true, message: "请输入故障描述" }]}
        >
          <TextArea rows={4} />
        </Form.Item>
        <Form.Item
          name="breakdownPart"
          label="故障部位"
          rules={[{ required: true, message: "请输入故障部位" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="breakdownReason"
          label="故障原因"
          rules={[{ required: true, message: "请输入故障原因" }]}
        >
          <TextArea rows={4} />
        </Form.Item>
        <Form.Item
          name="repairMethod"
          label="维修方法"
          rules={[{ required: true, message: "请输入维修方法" }]}
        >
          <TextArea rows={4} />
        </Form.Item>
        <Form.Item name="suggestion" label="预防建议">
          <TextArea rows={4} />
        </Form.Item>
      </Form>
    </>
  );
});

export default EamEquipmentRepairReportPage;
